﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PMS.Logic.FM
{
    public partial class InvoiceAjax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String methodName = Request["method"];
            Type type = this.GetType();
            MethodInfo method = type.GetMethod(methodName);
            if (method == null) throw new Exception("method is null");
            try
            {

                method.Invoke(this, null);
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 获取所有发票信息
        /// </summary>
        public void GetInvoiceList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startSignDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startSignDate").FirstOrDefault().Field = "Date";
                }
                if (listSearch.Where(s => s.Field == "endSignDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endSignDate").FirstOrDefault().Field = "Date";
                }
            }
            Expression<Func<View_FM_InvoiceList, bool>> exp = SearchExpression.FindByGroup<View_FM_InvoiceList>(listSearch);
            string OrderId = OperateContext.Sort == null ? "ID" : OperateContext.Sort;
            Boolean OrderSort = OperateContext.Order == true ? OperateContext.Order : false;
            if (OperateContext.Sort == null)
            {
                OrderSort = false;
            }
            int count = 0;
            var list = DALSession.Current.View_FM_InvoiceListDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, OrderSort);
            count = DALSession.Current.View_FM_InvoiceListDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }

        /// <summary>
        /// 根据发票ID获取发票信息
        /// </summary>
        public void GetInvoiceById()
        {
            if (Request.Form["Id"] == null)
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "获取参数Id失败"));
            }
            int Id = Convert.ToInt32(Request.Form["Id"]);
            Response.Write(JsonHelper.toJson(DALSession.Current.View_FM_InvoiceListDAL.GetListBy(i => i.ID == Id).FirstOrDefault()));
        }

        /// <summary>
        /// 修改发票信息
        /// </summary>
        public void EditInvoice()
        {
            int ID = Commons.String2Int32(Request.Form["ID"]);
            Boolean res = true;
            String msg = "";
            FM_Invoice perNew = DALSession.Current.FM_InvoiceDAL.GetListBy(d => d.ID == ID).FirstOrDefault();
            ModelTools.Form2EditModel(Request.Form, perNew);
            if (checkInvoice(perNew, msg))
            {
                DALSession.Current.FM_InvoiceDAL.ModifyAllModel(perNew);
                DALSession.Current.FM_InvoiceDAL.SaveChanges();
                msg = "保存成功！";
            }
            else {
                res = false;
            }
            Response.Write(JsonHelper.toDefaultMsg(res, msg));
        }

        /// <summary>
        /// 添加发票信息
        /// </summary>
        public void AddInvoice()
        {
            Boolean res = true;
            String msg = "";
            FM_Invoice per = new FM_Invoice();
            ModelTools.Form2EditModel(Request.Form, per);
            per.State = "0";
            if (checkInvoice(per, msg))
            {
                DALSession.Current.FM_InvoiceDAL.Add(per);
                DALSession.Current.FM_InvoiceDAL.SaveChanges();
                msg = "保存成功！";
            }
            else {
                res = false;
            }
            //// 更新合同的开票状态
            //if (per.ContractID != null&&!"".Equals(per.ContractID)) {
            //    CM_Contract mod = DALSession.Current.CM_ContractDAL.GetListBy(co => co.ID == per.ContractID).FirstOrDefault();
            //    if (null!=mod) {
            //        mod.IsInvoice = "1";
            //        mod.InvoiceDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //        DALSession.Current.CM_ContractDAL.ModifyAllModel(mod);
            //        DALSession.Current.CM_ContractDAL.SaveChanges();
            //    }
            //}
            Response.Write(JsonHelper.toDefaultMsg(res, msg));
        }

        /// <summary>
        /// 删除发票信息
        /// </summary>
        public void DelInvoice()
        {
            int Id = Convert.ToInt32(Request.Form["Id"].ToString());
            DALSession.Current.FM_InvoiceDAL.DelBy(p => p.ID == Id);
            DALSession.Current.FM_InvoiceDAL.SaveChanges();
            //FM_Invoice delIn = DALSession.Current.FM_InvoiceDAL.GetListBy(li => li.ID == Id).FirstOrDefault();
            //// 更新合同的开票状态
            //if (null != delIn.ContractID && !"".Equals(delIn.ID)) {
            //    var list = DALSession.Current.FM_InvoiceDAL.GetListBy(li => li.ContractID == delIn.ID);
            //    if (list.Count() ==0) {
            //        CM_Contract contract = DALSession.Current.CM_ContractDAL.GetListBy(li => li.ID == delIn.ContractID).FirstOrDefault();
            //        contract.IsInvoice = "0";
            //        contract.InvoiceDate = "";
            //        DALSession.Current.CM_ContractDAL.ModifyAllModel(contract);
            //        DALSession.Current.CM_ContractDAL.SaveChanges();
            //    }
            //}
            Response.Write(JsonHelper.toDefaultMsg(true, "删除成功"));
        }

        /// <summary>
        /// 核销发票
        /// </summary>
        public void verifyInvoice() { 
            int id=Convert.ToInt32(Request.Form["Id"].ToString());
            FM_Invoice per = DALSession.Current.FM_InvoiceDAL.GetListBy(i => i.ID == id).FirstOrDefault();
            Boolean res = true;
            String msg = "";
            // 检查发票金额是否已核销完成
            decimal gjMoney = 0;
            var reciivePays = DALSession.Current.View_FM_InvoicePayDAL.GetListBy(iP => iP.InvoiceID == per.ID);
            reciivePays.ForEach(rP => gjMoney += (decimal)rP.Money);
            if (gjMoney >= per.Money)
            {
                per.State = "2";
                DALSession.Current.FM_InvoiceDAL.ModifyAllModel(per);
                DALSession.Current.FM_InvoiceDAL.SaveChanges();
                msg = "发票核销成功！";
            }
            else {
                res = false;
                msg = "回款钩稽总金额小于发票金额，无法核销发票！";
            }
            Response.Write(JsonHelper.toDefaultMsg(res, msg));
        }

        /// <summary>
        /// 检查发票实体
        /// </summary>
        /// <param name="iv"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public Boolean checkInvoice(FM_Invoice iv,String msg) {
            Boolean res = true;
            if (String.IsNullOrEmpty(iv.InvoiceNo)) {
                res = false;
                msg = "发票单号不能为空！";
            }
            else if (String.IsNullOrEmpty(iv.Money.ToString())) {
                res = false;
                msg = "发票金额不能为空！";
            }
            return res;
        }

    }
}